#
# Copyright 2012 ibiblio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from rabbitmq_connector import RabbitMQConnector, BasicMessageHandler

class RabbitMQConsumer(RabbitMQConnector):
    def __init__(self, **kwargs):
        RabbitMQConnector.__init__(self, **kwargs)
        self._handler = kwargs.get('handler', None)
        if not self._handler:
            self._handler = BasicMessageHandler()

    def _preflight_check(self):
        RabbitMQConnector._preflight_check(self)
        if not self._queue_name:
            raise ValueError('Missing queue name')

    def _on_channel_open_stage2(self):
        """
        Called by RabbitMQConnector::on_channel_open
        """
        self._declare_queue(self.on_queue_declared)

    def on_queue_declared(self, frame):
        self._log.info('Queue declared (%s)' % (self._queue_name))
        self._bind_queue()

    def _bind_queue(self):
        if self._verbose:
            self._log.info('Calling queue_bind (exchange: %s, queue: %s)' % (self._exchange, self._queue_name))
        self._channel.queue_bind(exchange=self._exchange,
                                 queue=self._queue_name,
                                 routing_key=self._queue_name,
                                 callback=self.on_queue_bound)

    def on_queue_bound(self, frame):
        self._log.info('Queue bound (queue: %s)' % (self._queue_name))
        self._set_ready()
        self._channel.basic_consume(self.handle_delivery, queue=self._queue_name)

    def handle_delivery(self, channel, method, header, body):
        self._handler.handle(channel, method, header, body)
